#!/usr/bin/env python
# -*- coding: utf-8 -*

import os,commands,socket,sys
from files import *


class Zk():
    def __init__(self,config):
        for line in File().read(config):
            if 'user' in line.split('=')[0]:
                self.user = line.split('=')[-1].strip()
            if 'source_softdir' in line.split('=')[0]:
                self.source_softdir = line.split('=')[-1].strip()
            if 'version' in line.split('=')[0]:
                self.version = line.split('=')[-1].strip()
            if 'zknodes' in line.split('=')[0]:
                self.zknodes = line.split('=')[-1].strip()
                self.zklist =self.zknodes.split(',')
        self.bash_dir = "/home/%s/cdh5/zookeeper" % (self.user)
        self.zk_laster = "%s/latest" % (self.bash_dir)
        self.zoo = "%s/conf/zoo.cfg" % (self.zk_laster)
        #self.zoo = 'zoo.cfg'
        self.datadir = "%s/var/data" % (self.bash_dir)
        self.datalog = "%s/var/datalog" % (self.bash_dir)
        #环境变量
        self.bpfile = '/home/%s/.bash_profile' % self.user
        #self.bpfile = 'bash_profile'
        self.zk_home_export = "\nexport ZOOKEEPER_HOME=%s" %(self.zk_laster)
        self.zk_logdir_export = "\nexport ZOO_LOG_DIR=$ZOOKEEPER_HOME/logs"
        self.zk_path_export = '\nPATH=$ZOOKEEPER_HOME/bin:$ZOOKEEPER_HOME/sbin:$PATH'
        self.mkdatadir = "mkdir -p %s" % self.datadir
        self.datadirmyid = "%s/myid" % (self.datadir)
        self.mkdatalog = "mkdir -p %s" % self.datalog
        self.mkbashdir = "test -d %s || mkdir -p %s" % (self.bash_dir,self.bash_dir)
        self.zktar = "tar zxf %s/%s.tar.gz -C %s/" % (self.source_softdir,self.version,self.bash_dir)
        self.lnlatest = "ln -s %s/%s %s" % (self.bash_dir,self.version,self.zk_laster)
        self.lslaster = "ls -ld %s" % (self.zk_laster)
        self.lsdirs = "ls -l %s/var" % (self.bash_dir)
        self.change_ower = "chown %s:%s -R %s" % (self.user, self.user, self.bash_dir)
        self.zoo_demo = '''tickTime=6000
initLimit=20
syncLimit=5
syncLimit=20
clientPort=2181
maxClientCnxns=1500
dataDir=datadir
dataLogDir=datalog'''

        self.start_zkserver = "%s/bin/zkServer.sh  start" % (self.zk_laster)
        self.status_zkserver = "%s/bin/zkServer.sh status" % (self.zk_laster)
        # 开机自启动服务
        self.auto_start_zkserver = ''' echo "su - %s -c '%s >/dev/null 2>&1 ' " ''' % (self.user, self.start_zkserver)

        self.logfile = './logs/Install.log'
        info03 = "mkdatadir:%s\nmkdatalog:%s\nzoo_demo:%s\n" %(self.mkdatadir,self.mkdatalog,self.zoo_demo)
        info01 = "user:%s\n\nsource_softdir:%s\nversion:%s\nzknodes:%s\nbash_dir:%s\nzk_laster:%s\nzoo:%s\ndatadir:%s\ndatalog:%s\nlslaster:%s\nlsdirs:%s\n" \
        %(self.user,self.source_softdir,self.version,self.zknodes,self.bash_dir,self.zk_laster,self.zoo,self.datadir,self.datalog,self.lslaster,self.lsdirs)

        info02 = "bpfile：%s \nzk_home_export:%s\nzk_path_export:%s\n\nmkbashdir:%s\nzktar:%s\nlnlatest:%s\n" \
        %(self.bpfile,self.zk_home_export,self.zk_path_export,self.mkbashdir,self.zktar,self.lnlatest)
        #print info01,info02,info03
        File().add(self.logfile,info01)
        File().add(self.logfile,info02)
        File().add(self.logfile,info03)

    def init(self):

        #添加环境变量
        File().add(self.bpfile,self.zk_home_export)
        File().add(self.bpfile,self.zk_logdir_export)
        File().add(self.bpfile,self.zk_path_export)

        # 创建部署目录 ，tar 包解压缩
        commands.getoutput(self.mkbashdir)
        commands.getoutput(self.zktar)
        commands.getoutput(self.lnlatest)
        commands.getoutput(self.mkdatadir)
        commands.getoutput(self.mkdatalog)
        commands.getoutput(self.change_ower)
        lslasterinfo = commands.getoutput(self.lslaster)
        lsdirsinfo = commands.getoutput(self.lsdirs)
        #print lslasterinfo,lsdirsinfo
        File().add(self.logfile, (lsdirsinfo + '\n'))
        File().add(self.logfile, (lslasterinfo+'\n'))
    def modify(self):
        self.init()
        ip = self.get_host_ip()
        try:
            #修改配置文件
            File().write(self.zoo,self.zoo_demo)
            File().fileinput(self.zoo,'datadir',self.datadir)
            File().fileinput(self.zoo,'datalog',self.datalog)
            for id in xrange(len(self.zklist)):
                if ip == self.zklist[id]:
                    File().write(self.datadirmyid,str(id + 1))
                svr = "server.%d=%s:2888:3888\n" % ((id + 1), self.zklist[id])
                File().add(self.zoo, svr)
        except:
            File().add(self.logfile, ("configure changed failed !"))

    def get_host_ip(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            s.close()
        return ip

    def startsvr(self):
        self.modify()
        commands.getoutput(self.start_zkserver)
        status = commands.getoutput(self.status_zkserver)
        File().add(self.logfile,('\n'+ status))
        autostart = "\nStartUp Actions Manager:\nAdd %s to /etc/rc.local file by root !" % self.auto_start_zkserver
        File().add(self.logfile, autostart)
